package com.howie.shirojwt.controller;

import com.howie.shirojwt.enity.User;
import com.howie.shirojwt.service.UserService;
import com.howie.shirojwt.util.JWTUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user/")
public class NewController {
    @Autowired
    UserService userService;
    @PostMapping("login")
    public String login(User user, HttpServletResponse response) {
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            String jwt = JWTUtil.createToken(user.getUsername());
            response.setHeader("Token", jwt);
            return "成功!";
        } catch (Exception e) {
            return e.toString();
        }
        /*User loginUser = userService.getUser(user.getUsername());
        if(loginUser.getPassword().equals(user.getPassword())){
            String jwt = JWTUtil.createToken(user.getUsername());
            response.setHeader("token", jwt);
            return "成功!";
        }else{
            return "失败";
        }*/
    }
    @PostMapping("index")
    public String index(HttpServletRequest request){
        String token = request.getHeader("Token");
        return "欢迎"+token;
    }


}
